package com.yunduo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.RetunData.statuscode.impl.ServiceCode;
import com.yunduo.entity.Good;
import com.yunduo.entity.GoodType;
import com.yunduo.entity.vo.TreeData;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.mapper.GoodTypeMapper;
import com.yunduo.service.GoodService;
import com.yunduo.service.GoodTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChengXin
 * @since 2023-07-12
 */
@Service
public class GoodTypeServiceImpl extends ServiceImpl<GoodTypeMapper, GoodType> implements GoodTypeService {

    @Resource
    private GoodService goodService;
    //删除树形结构 分类数据
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTreeData(TreeData treeData){
        List<TreeData> children = treeData.getChildren();
        for (int i = 0; i < children.size(); i++) {
            if(children.get(i).getChildren() == null || children.get(i).getChildren().size() == 0){
                Good isExist = goodService.getOne(new LambdaQueryWrapper<Good>().eq(Good::getType, children.get(i).getId()));
                if(isExist != null){
                    throw new OperationException(ServiceCode.TYPE_IS_BLOCK);
                }
                this.removeById(children.get(i).getId());
                children.remove(i);
                continue;
            }
            deleteTreeData(children.get(i));
            //遍历到底层,开始递归删除
        }
        Good isExist = goodService.getOne(new LambdaQueryWrapper<Good>().eq(Good::getType, treeData.getId()));
        if(isExist != null){
            throw new OperationException(ServiceCode.TYPE_IS_BLOCK);
        }
        this.removeById(treeData.getId());
        return true;
    }
}
